package com.stylefeng.guns.modular.charon.controller;

import com.stylefeng.guns.common.persistence.dao.PcServerInfoMapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;


@Controller
@RequestMapping("/app")
public class AppController extends BaseController {
    private String PREFIX = "/charon/app/";
    @Resource
    PcServerInfoMapper pcServerInfoMapper;


    @RequestMapping("")
    public String index(Model model) {
        model.addAttribute("path", "http://localhost:8081/charon/");
        return PREFIX + "appDownload.html";
    }
    @RequestMapping("/upload")
    public String upload(Model model) {
        model.addAttribute("path", "http://localhost:8081/charon/");
        return PREFIX + "appUpload.html";
    }
    @RequestMapping(value = "/uploadApp", method = RequestMethod.POST)
    @ResponseBody
    public String uploadApp(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            FileOutputStream fileOutputStream = null;
            try {
                String webRootPath = this.getClass().getResource("/").getPath();
                String path = "static/app/";
                File file1 = new File(webRootPath + path + file.getOriginalFilename());
                if (!file1.exists()) {
                    File dir = new File(file1.getParent());
                    dir.mkdirs();
                    file1.createNewFile();
                }

                fileOutputStream = new FileOutputStream(file1);
                IOUtils.write(file.getBytes(),fileOutputStream);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }finally {
                IOUtils.closeQuietly(fileOutputStream);
            }
            return "上传成功";
        } else {
            return "上传失败，因为文件是空的.";
        }
    }

}
